<style>
    div[lay-id="productionPlanTable"] .layui-table-cell {
      padding: 0 5px;
    }
  
    .table-auto .layui-table-cell {
      height: auto;
    }
  
    .template-box .w-auto {
      width: 110px !important;
      text-align: left;
      padding: 9px 0;
    }
  
    .template-box .addTable {
      height: 30px;
      line-height: 30px;
      padding: 0 10px;
    }
  
    .msg-none .layui-none {
      display: none !important;
    }
  
    .flex-item {
      display: flex;
      border-bottom: 1px solid #e6e6e6;
    }
  
    .left-btn {
      flex: 1;
      text-align: left;
    }
  
    .flex-between {
      width: calc(100% - 40px);
      display: flex;
      justify-content: space-between;
    }
  
    body .layui-table tbody tr.disabledBg {
      background-color: #f5f5f5 !important;
    }
  
    .layui-table-page-left {
      text-align: left;
    }
  
    .scroll-table-5-4 .layui-table-body {
      max-height: 535px;
    }
  
    .scroll-table-4-5 .layui-table-body {
      max-height: 490px;
    }
  
    /*   添加生产计划   */
    .addProductionPlanForm-title,
    .examineProductionPlanForm-title {
      width: 100%;
    }
  
    .addProductionPlanForm-title .title,
    .examineProductionPlanForm-title .title {
      display: inline-block;
      font-size: 16px;
      font-weight: bold;
      color: #333333;
      line-height: 19px;
      position: relative;
      padding: 6px 0 19px 0;
    }
  
    .addProductionPlanForm-title .title:after,
    .examineProductionPlanForm-title .title:after {
      content: "";
      display: block;
      position: absolute;
      left: 0;
      bottom: 0;
      width: calc(100% + 6px);
      height: 3px;
      background: #0a8b0a;
    }
  
    .line {
      width: 100%;
      height: 1px;
      background-color: #f8f8f8;
    }
  
    .addProductionPlanFormBox {
      padding: 20px 0;
    }
  
    .addProductionPlanFormBox .layui-col-md4 {
      margin: 5px 0;
    }
  
    .addProductionPlanFormBox .layui-form-label,
    addProductionPlanFormItem .layui-form-label {
      padding: 9px;
      width: 115px;
      font-size: 14px;
      font-weight: 400;
      color: #999999;
    }
  
    .addProductionPlanFormBox .layui-input-inline>input[readonly] {
      border-color: rgba(0, 0, 0, 0);
      outline: none;
    }
  
    .addProductionPlanFormBox .layui-input-inline>input[readonly]:focus,
    .addProductionPlanFormBox .layui-input-inline>input[readonly]:hover {
      border-color: transparent !important;
      outline: none;
    }
  
    form[lay-filter="examineProductionPlanForm"] textarea {
      width: 90%;
      resize: none;
      padding: 5px 10px;
      height: 100px;
      box-sizing: border-box;
    }
  
    form[lay-filter="examineProductionPlanForm"] .layui-table-cell {
      height: auto;
    }
  
    form[lay-filter="examineProductionPlanForm"] .layui-table-cell>img {
      height: 100%;
    }
  
    .addProductionPlanFormItem {
      padding: 15px 0 0 0;
    }
  
    .addProductionPlanFormItem .layui-input-block {
      margin-left: 133px;
      padding-right: 90px;
      box-sizing: border-box;
    }
  
    .open-details-box::-webkit-scrollbar {
      width: 0 !important;
    }
  </style>
  <form lay-filter="addProductionPlanFormDiv" class="layui-form open-form">
    <div class="open-model" id="addProductionPlanFormContent">
      <div class="open-auto">
        <input type="hidden" name="id" />
        <input type="hidden" name="productTypeName" />
        <input type="hidden" name="materialNatureName" />
        
        <div class="layui-form-item">
            <!-- <div class="addProductionPlanForm-title">
              <h3 class="title">信息</h3>
            </div> -->
            <div class="line"></div>
            <div class="layui-form-item layui-row addProductionPlanFormBox">
                <div class="layui-inline layui-col-md4">
                  <label class="layui-form-label">企业编号：</label>
                  <div class="layui-input-inline">
                    <input name="enterpriseCode" class="layui-input" type="text" />
                  </div>
                </div>
                
                <div class="layui-inline layui-col-md4">
                  <label class="layui-form-label">计件工资单编号：</label>
                  <div class="layui-input-inline">
                    <input name="code" class="layui-input" type="text" />
                  </div>
                </div>
                
                <div class="layui-inline layui-col-md4">
                  <label class="layui-form-label">所属月份：</label>
                  <div class="layui-input-inline">
                    <input name="month" class="layui-input" type="text" />
                  </div>
                </div>
                
                <div class="layui-inline layui-col-md4">
                  <label class="layui-form-label">报工单数：</label>
                  <div class="layui-input-inline">
                    <input name="workQuantity" class="layui-input" type="text" />
                  </div>
                </div>
                
                <div class="layui-inline layui-col-md4">
                  <label class="layui-form-label">合格工资：</label>
                  <div class="layui-input-inline">
                    <input name="qualifiedSalary" class="layui-input" type="text" />
                  </div>
                </div>
                
                <div class="layui-inline layui-col-md4">
                  <label class="layui-form-label">不合格工资：</label>
                  <div class="layui-input-inline">
                    <input name="unqualifiedSalary" class="layui-input" type="text" />
                  </div>
                </div>
                
                <div class="layui-inline layui-col-md4">
                  <label class="layui-form-label">报废罚款：</label>
                  <div class="layui-input-inline">
                    <input name="scrapPenalty" class="layui-input" type="text" />
                  </div>
                </div>
                
                <div class="layui-inline layui-col-md4">
                  <label class="layui-form-label">计件金额：</label>
                  <div class="layui-input-inline">
                    <input name="pieceRateAmount" class="layui-input" type="text" />
                  </div>
                </div>
                
                <div class="layui-inline layui-col-md4">
                  <label class="layui-form-label">状态：</label>
                  <div class="layui-input-inline">
                    <select name="status" class="layui-input">
                      <option value="">请选择状态</option>
                      <option value="0">待确认</option>
                      <option value="1">已确认</option>
                      <option value="2">待结算</option>
                      <option value="3">已结算</option>
                    </select>
                  </div>
                </div>
                
                <div class="layui-inline layui-col-md4">
                  <label class="layui-form-label">员工确认时间：</label>
                  <div class="layui-input-inline">
                    <input name="empConfirmTime" class="layui-input" type="text" id="empConfirmTime" placeholder="yyyy-MM-dd HH:mm:ss" />
                  </div>
                </div>
                
                <div class="layui-inline layui-col-md4">
                  <label class="layui-form-label">财务确认时间：</label>
                  <div class="layui-input-inline">
                    <input name="financeConfirmTime" class="layui-input" type="text" id="financeConfirmTime" placeholder="yyyy-MM-dd HH:mm:ss" />
                  </div>
                </div>
                
                <div class="layui-inline layui-col-md4">
                  <label class="layui-form-label">结算时间：</label>
                  <div class="layui-input-inline">
                    <input name="settlementTime" class="layui-input" type="text" id="settlementTime" placeholder="yyyy-MM-dd HH:mm:ss" />
                  </div>
                </div>
              </div>
          </div>

          <table class="layui-table" id="relevanceMaterialTable" lay-filter="relevanceMaterialTable"></table>
        
      </div>
  </form>
  <script type="text/html" id="skuPlanTableBar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="del">删除</a>
  </script>
  <script>
    layui.use(["form", "table", "admin", "jquery", "laydate"], async function () {
      let form = layui.form;
      let table = layui.table;
      let admin = layui.admin;
      let $ = layui.jquery;
      let laydate = layui.laydate;
      const nowData = { ...parentData };
      console.log('nowData', nowData);
  
      let data = nowData.data;
      let orderObj = {
        customerSkuCode: "",
        productDetailId: "",
        orderProId: "",
        customerSkuName: "",
        customerSkuSpec: "",
        productTypeId: "",
        productTypeId: "",
        productTypeName: "",
        productNatureName: "",
        bookId: "",
        bookId: "",
        processName: "",
        processId: "",
        residueQuantity: "",
        shipmentTime: "",
        demandQuantity: "",
        productionQuantity: "",
        outputTime: "",
        orderRemark: "",
        accessory: "",
        remark: "",
      };
      let initOrderObj = {
        shipmentTime: "",
        orderRemark: "",
        orderCreatorName: "",
        signOrNot: "",
        signOrNotDesc: "",
        contractName: "",
        contractId: "",
      };
      let initSkuObj = {
        orderProId: "",
        customerSkuCode: "",
        productDetailId: "",
        customerSkuName: "",
        customerSkuSpec: "",
        residueQuantity: "",
        demandQuantity: "",
        productTypeId: "",
        productTypeName: "",
        orderProId: "",
        bookId: "",
        processId: "",
      };
      const deviceRes = await admin
        .initDataSelectPro(
          "enterprise/device/admin/deviceWorkshop/list",
          {},
          "workshopId",
          "车间",
          () => { },
          "name"
        )
      const deviceList = deviceRes.map((v) => {
        return {
          label: v.name,
          value: v.id,
        };
      });
      
  
      if (
        nowData.planSourceType == "order" ||
        nowData.planSourceType == "finish"
      ) {
        let type = nowData.planSourceType
        $("#planSource").val(nowData.planSourceType);
        $("#planSource").attr("disabled", true);
        $("#orderFun").hide();
        console.log("nowData", nowData);
        form.val("addProductionPlanFormDiv", {
          orderId: nowData.orderId,
          orderCode: nowData.orderCode,
        });
        let detailUrl = "";
        if (type == "order") {
          detailUrl = "enterprise/sell/admin/order/detail/";
        } else if (type == "finish") {
          detailUrl = "enterprise/sell/admin/finishedOrder/detail/";
        }
        const res = await admin.reqPro(detailUrl + nowData.orderId);
        let obj = res.data;
        let list = [];
        if (type == "order") {
         await initSkuPlanTable(
            obj.orderProList,obj
          );
          form.val("addProductionPlanFormDiv", {
            orderId: obj.id,
            orderCode: obj.code,
          });
        } else if (type == "finish") {
          await initSkuPlanTable(obj.details,obj);
          form.val("addProductionPlanFormDiv", {
            orderId: obj.id,
            orderCode: obj.selCode,
            // shipmentTime: obj.deliveryTime,
          });
        }
        isOrderFun(true);
  
      }
      else if(nowData.planSourceType=="single"){
        $("#addSkuPianFun").hide(); 
        $("#planSource").val("temporary");
        $("#planSource").attr("disabled", true);
        initSkuPlanTable([nowData]);
      }
      if (nowData.eventName === "detail") {
        $("#customerSkuCode").attr("disabled", true);
        $("#planSource").attr("disabled", true);
        $("#planInfoBox").show();
        $("#orderFun").hide();
        $("#orderIdBox").show();
        $(".addProductionPlanFormBox").show();
        $("#skuPlanTableBox").hide();
        admin.setFormDisable("#addProductionPlanFormContent", true);
      } else if (nowData.eventName === "edit") {
        $("#customerSkuCode").attr("disabled", true);
        $("#planSource").attr("disabled", true);
        $('#skuPlanTableBox').hide()
        $(".addProductionPlanFormBox").show();
  
      } else {
        $("#planInfoBox").hide();
      }
  
      // 让所有div显示
      // $(".layui-col-md4").show();
      init();
      async function init() {
        await initCreateData(); // 确保所有initDataForm中的异步操作完成
        await initFormByType(nowData.type); // 然后执行initFormByType
        initDataForm(nowData.id);
      }
  
      // const xx = await admin.initDataSelectPro(
      //   "enterprise/device/admin/deviceWorkshop/list",
      //   {},
      //   "workshopId",
      //   "车间",
      //   () => {},
      //   "name"
      // );
      // console.log(1, xx);
   
     
      table.on("tool(skuPlanTable)", function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        var field = $(this).data("field");
        let tableList = table.cache["skuPlanTable"];
        var index = $(obj.tr).data("index");
  
        if (obj.event === "checkBook") {
          admin.putTempData("benData", data ? data : null);
          admin.formOpen({
            area: "1400px",
            offset: "35px",
            title: "基准书管理",
            path: "components/product/benManager.html",
            success: function () {
              parentData.typeName = "redio";
            },
            end: async function () {
              let objData = childData.obj ? childData.obj : {};
              if (objData.statusName == "待初审") {
                layer.msg("基准书状态为待初审，无法生成生产计划！", { icon: 2 });
                return false;
              }
  
              data["bookId"] = objData.id;
              data["bookCode"] = objData.code;
              obj.update(data);
              console.log(123, obj);
  
              console.log(table.cache["skuPlanTable"]);
  
              table.reload("skuPlanTable");
            },
          });
        } else if (obj.event === "editStartDate") {
          laydate.render({
            elem: this.firstChild,
            show: true, //直接显示
            type: "datetime",
            // closeStop: this,
            done: function (value, date) {
              // admin.setTableColHtml("skuPlanTable", index, field, value)
              table.cache["skuPlanTable"][index][field] = value;
              // data[field] = value;
              // obj.update(data);
              // table.reload("skuPlanTable", { data: tableList });
              console.log(table.cache["skuPlanTable"]);
            },
          });
        } else if (obj.event === "del") {
          // let list = xxxList[nodeIndex].processDeviceList;
          // list = list.filter((v) => {
          //   return v["id"] != id;
          // });
          // xxxList[nodeIndex].processDeviceList = list;
          tableList = tableList.filter((v) => {
            return v["productDetailId"] != data.productDetailId;
          });
          // obj.del();
          // tableList.splice(index, 1);
          console.log(tableList);
          table.reload("skuPlanTable", { data: tableList });
        }
      });
      async function initCreateData() {
        laydate.render({
          elem: "#plannedOutputTime",
          type: "datetime",
        });
  
        laydate.render({
          elem: "#addProductionPlanDeliveryTime",
          type: "datetime",
        });
        form.on("select(planSource)", function (d) {
          form.val("addProductionPlanFormDiv", {
            ...orderObj,
            orderId: "",
            orderCode: "",
          });
          console.log(3333);
          
          table.reload("skuPlanTable", { data: [] });
          if (d.value == "order" || d.value == "finish") {
            isOrderFun(true);
            $("#addSkuPianFun").hide();
          } else {
            $("#addSkuPianFun").show();
  
            isOrderFun(false);
          }
        });
        //订单类型
        // await admin.getDictListPro("orderType", "production_plan_order_type", "订单类型");
        //计划性质
        await admin.getDictListPro(
          "planNature",
          "production_plan_nature",
          "计划性质",
          (d, obj) => {
            if (d.value == "entirety") {
              //整体生产计划'
              $("#processIdBox").hide({ duration: 300 });
            } else if (d.value == "process") {
              $("#processIdBox").show({ duration: 300 });
            }
          }
        );
        //计划类型
        await admin.initDataSelectPro(
          "production/productionPlan/admin/productionType/list",
          { businessProperty: 1, page: 1, limit: 9999 },
          "planTypeId",
          "计划类型",
          () => { },
          "name"
        );
  
        //计划分类
        // admin.initDataSelectTree(
        //   true,
        //   "production/productionPlan/admin/productionCategory/getTreeData",
        //   null,
        //   "selectPlanClassify",
        //   data ? data?.planClassifyId : null,
        //   "计划分类",
        //   "planClassifyId",
        //   null
        // );
      }
      async function initDataForm(id) {
        if (id) {
          const { data } = await admin.reqPro(
            "production/productionPlan/admin/productionPieceRate/detail/"+id,
            {  }
          );
          console.log('data', data);
        //   await initBenchmarkBookData(data.productDetailId);
          form.val("addProductionPlanFormDiv", data);
           // 关联物料表格
           table.render({
                    elem: "#relevanceMaterialTable",
                    data: data.pieceRateDetailList,
                    cellMinWidth: 100,
                    page: false,
                    cols: [
  [
                      { type: "numbers", width: 40, title: "序号" },
                      { field: "enterpriseCode", title: "企业编号", align: "center", width: 100 },
                      { field: "skuCode", title: "产品料号", align: "center", width: 120 },
                      { field: "processName", title: "所属工序", align: "center", width: 120 },
                      { field: "theWorkOrderPeopleName", title: "报工人", align: "center", width: 100 },
                      { 
                        field: "salaryQuota", 
                        title: "合格单价", 
                        align: "center", 
                        width: 100,
                        templet: function(d) {
                          return d.salaryQuota ? d.salaryQuota + "元/pcs" : "-";
                        }
                      },
                      { 
                        field: "reportedQuantity", 
                        title: "报工数量", 
                        align: "center", 
                        width: 100,
                        templet: function(d) {
                          return d.reportedQuantity ? d.reportedQuantity + "PCS" : "-";
                        }
                      },
                      { 
                        field: "okQuantity", 
                        title: "合格数", 
                        align: "center", 
                        width: 100,
                        templet: function(d) {
                          return d.okQuantity ? d.okQuantity + "pcs" : "-";
                        }
                      },
                      { 
                        field: "okSalary", 
                        title: "合格薪资", 
                        align: "center", 
                        width: 100,
                        templet: function(d) {
                          return d.okSalary ? "￥" + d.okSalary : "-";
                        }
                      },
                      { 
                        field: "qualifiedNoQuantity", 
                        title: "不合格数", 
                        align: "center", 
                        width: 100,
                        templet: function(d) {
                          return d.qualifiedNoQuantity ? d.qualifiedNoQuantity + "pcs" : "-";
                        }
                      },
                      { 
                        field: "qualifiedNoSalary", 
                        title: "不合格薪资", 
                        align: "center", 
                        width: 100,
                        templet: function(d) {
                          return d.qualifiedNoSalary ? "￥" + d.qualifiedNoSalary : "-";
                        }
                      },
                      { 
                        field: "status", 
                        title: "状态", 
                        align: "center", 
                        width: 100,
                        templet: function(d) {
                          const statusMap = { 0: "待确认", 1: "已确认", 2: "待结算", 3: "已结算" };
                          return statusMap[d.status] || "未知";
                        }
                      },
                      { field: "confirmTime", title: "确认时间", align: "center", width: 150 }                    ]
]
                  });
        }
      }
      async function initFormByType(type) {
        if (nowData.productDetailId) {
          if (type === "基准书生成") {
            // 基准书
            $("#customerSkuCode").attr("disabled", true);
            form.val("addProductionPlanFormDiv", {
              planSource: "research",
            });
            $("#planSource").attr("disabled", true);
            initSkuData(nowData.productDetailId);
            initBenchmarkBookData(nowData.productDetailId);
          }
        } else {
          $("#checkSkuFun").show();
        }
      }
      // 赋值物料
      async function initSkuData(productDetailId) {
        const { data } = await admin.reqPro(
          "enterprise/product/admin/productDetailWMS/get",
          { productDetailId }
        );
        form.val("addProductionPlanFormDiv", {
          customerSkuCode: data.skuCode,
          customerSkuName: data.skuName,
          customerSkuSpec: data.skuSpec,
          // residueQuantity: data.residueQuantity,
          demandQuantity: data.quantity,
          productTypeId: data.productDetailId,
          productDetailId: data.productDetailId,
          productTypeName: data.productTypeName,
          orderProId: data.orderProId,
        });
      }
      // 赋值基准书
      async function initBenchmarkBookData(productDetailId) {
        const resData = await admin.initDataSelectPro(
          "enterprise/benchmarkBook/admin/benchmarkBook/getBookInfoBy/" +
          productDetailId,
          {},
          "bookId",
          "基准书",
          async (d, obj) => {
            form.val("addProductionPlanFormDiv", {
              accessoryFileId: "",
            });
            $("#processId").empty();
            $("#accessoryPath").html(
              "<span style='cursor: default;'>暂无附件</span>"
            );
            // $("#accessoryBtn").show();
            if (d.value) {
              // await admin.initDataSelectPro(
              //   "enterprise/benchmarkBook/admin/benchmarkBook/getEchnologyBy/" +
              //   d.value,
              //   {},
              //   "processId",
              //   "工序",
              //   (d, obj) => {
              //     console.log(111, obj);
              //     if (d.value) {
              //       form.val("addProductionPlanFormDiv", {
              //         processName: obj.name,
              //       });
              //     }
              //   }
              // );
              if (obj.drawUrl) {
                form.val("addProductionPlanFormDiv", {
                  accessoryFileId: obj.drawUrl,
                });
                $("#accessoryPath").html(
                  "<a href='" +
                  obj.drawUrl +
                  "' target='_blank'>" +
                  obj.drawUrl +
                  "</a>"
                );
                // $("#accessoryBtn").hide();
                $("#accessoryFileId").val(obj.drawUrl);
              }
            }
            form.render();
          },
          "code"
        );
        // if (resData.length == 0) {
        //   //弹窗是否跳转
        //   layer.confirm("当前物料没有基准书，是否跳转新增基准书弹窗？", { icon: 3, title: "提示" }, function (index) {
        //     // 关闭所有弹窗
        //     layer.closeAll();
        //     // window.location.href = '/admin/index.html#/res/planning/proTask';
        //     admin.formOpen({
        //       area: ["80%", "88%"],
        //       title: "生成基准书",
        //       path: "components/res/benchmarkBook/skuPlanTable.html",
        //       success: function () {
        //         parentData.eventName = "add";
        //         delete data.id;
        //         parentData.data = data;
        //         // 关闭最近弹窗
        //       }
        //     });
        //   });
        // } else {
        // }
      }
  
      // 是否是订单
      function isOrderFun(isTrue) {
        if (isTrue) {
          $("#orderIdBox").show();
          $('#addSkuPianFun').hide()
          // $("#orderTypeBox").show();
          // $("#orderCreatorNameBox").show();
          $("#residueQuantityBox").show();
          $("#orderRemarkBox").show();
          $("#demandQuantity").attr("disabled", true);
          $("#demandQuantityBox").show();
        } else {
          $("#orderIdBox").hide();
          $("#residueQuantityBox").hide();
          $("#orderRemarkBox").hide();
          $("#demandQuantity").attr("disabled", false);
          $("#demandQuantityBox").hide();
        }
      }
      $("#customerSkuCode").click(function () {
        //计划来源
        let planSource = $("#planSource").val();
        let orderId;
        if (planSource === "order") {
          orderId = $("#orderId").val();
          if (orderId === "" || orderId === undefined) {
            layer.msg("请选择订单编号", { icon: 2 });
            return false;
          }
        }
        admin.formOpen({
          area: ["80%", "85%"],
          title: "物料列表",
          style: "font-size: 20px;",
          path: "components/productionPlan/product_detail.html",
          success: function () {
            parentData.orderId = orderId;
            parentData.planId = data.id ? data.id : null;
          },
          end: function () {
            console.log(111);
            console.log(form.val("addProductionPlanFormDiv"));
          },
        });
        return false;
      });
      $("#addSkuPianFun").click(function () {
        let planSource = $("#planSource").val();
        if (!planSource) {
          layer.msg("请选择计划来源", { icon: 2 });
          return false;
        }
        let orderId = "";
        if (planSource === "order" || planSource === "finish") {
          orderId = $("#orderId").val();
          if (orderId === "" || orderId === undefined) {
            layer.msg("请选择订单编号", { icon: 2 });
            return false;
          }
        }
        admin.formOpen({
          area: ["80%", "85%"],
          title: "物料列表",
          style: "font-size: 20px;",
          path: "components/purchase/skuTableForm.html",
          success: function () {
            parentData.orderId = orderId;
            parentData.notInListIds = table.cache["skuPlanTable"]
              .map((v) => v.productDetailId)
              .join();
            // parentData.type = $("#planSource").val();
          },
          end: function () {
            if (childData.list && childData.list.length > 0) {
              let list = table.cache["skuPlanTable"];
              let chidList = childData.list.map((v) => {
                v.customerSkuCode = v.skuCode;
                v.customerSkuName = v.skuName;
                v.customerSkuSpec = v.skuSpec;
                v.planNature = "entirety";
                v.outputTime = "";
                v.shipmentTime = "";
                v.bookId = "";
                v.bookCode = "";
                v.remark = "";
              });
              list.push(...childData.list);
  
              table.reload("skuPlanTable", { data: list });
            }
  
            // let productDetailId = $("#productDetailId").val();
            // if (orderId) {
            //   let planSource = $("#planSource").val();
            //   // const { data } = await admin.reqPro("enterprise/sell/admin/order/detail/" + orderId, {});
            //   if (productDetailId) {
            //     const { data } = await admin.reqPro(
            //       `production/productionPlan/admin/productionPlan/getQuantityBy/${orderId}/${planSource}/${productDetailId}`
            //     );
            //     // let obj = data.orderProList.find((v) => v.productDetailId == productDetailId);
            //     form.val("addProductionPlanFormDiv", {
            //       demandQuantity: data.quality,
            //       residueQuantity: data.noQuantityNum,
            //       productionQuantity:
            //         data.noQuantityNum > 0 ? data.noQuantityNum : 0,
            //     });
            //     // $("#orderProId").val(orderProId);
            //   }
            // } else {
            // }
            // if (productDetailId) {
            //   console.log("productDetailId", productDetailId);
            //   initBenchmarkBookData(productDetailId);
            // }
          },
        });
        return false;
      });
      $("#checkSkuFun").click(function () {
        //计划来源
        let planSource = $("#planSource").val();
        let orderId = "";
        if (planSource === "order" || planSource === "finish") {
          orderId = $("#orderId").val();
          if (orderId === "" || orderId === undefined) {
            layer.msg("请选择订单编号", { icon: 2 });
            return false;
          }
        }
        admin.formOpen({
          area: ["80%", "85%"],
          title: "物料列表",
          style: "font-size: 20px;",
          path: "components/productionPlan/product_detail.html",
          success: function () {
            parentData.orderId = orderId;
            parentData.type = $("#planSource").val();
          },
          end: async function () {
            let productDetailId = $("#productDetailId").val();
            if (orderId) {
              let planSource = $("#planSource").val();
              // const { data } = await admin.reqPro("enterprise/sell/admin/order/detail/" + orderId, {});
              if (productDetailId) {
                const { data } = await admin.reqPro(
                  `production/productionPlan/admin/productionPlan/getQuantityBy/${orderId}/${planSource}/${productDetailId}`
                );
                // let obj = data.orderProList.find((v) => v.productDetailId == productDetailId);
                form.val("addProductionPlanFormDiv", {
                  demandQuantity: data.quality,
                  residueQuantity: data.noQuantityNum,
                  productionQuantity:
                    data.noQuantityNum > 0 ? data.noQuantityNum : 0,
                });
                // $("#orderProId").val(orderProId);
              }
            } else {
            }
            if (productDetailId) {
              console.log("productDetailId", productDetailId);
              initBenchmarkBookData(productDetailId);
            }
          },
        });
        return false;
      });
  
      $("#orderFun").click(function () {
        let type = $("#planSource").val();
        let title = "";
        let path = "";
        let detailUrl = "";
        if (type == "order") {
          title = "量产订单列表";
          path = "components/sell/massOrder.html";
          detailUrl = "enterprise/sell/admin/order/detail/";
        } else if (type == "finish") {
          title = "完成订单列表";
          path = "components/sell/finishedOrder.html";
          detailUrl = "enterprise/sell/admin/finishedOrder/detail/";
        }
        if (type && path && title) {
          admin.formOpen({
            area: ["80%", "85%"],
            title: title,
            path: path,
            success: function () {
              parentData.eventName = "radio";
            },
            end: async function () {
              form.val("addProductionPlanFormDiv", { ...orderObj });
              if (childData.list && childData.list.length > 0) {
                const res = await admin.reqPro(detailUrl + childData.list[0].id);
                let obj = res.data;
                let list = [];
                if (type == "order") {
                  await initSkuPlanTable(
                    obj.orderProList,obj
                  );
                  form.val("addProductionPlanFormDiv", {
                    orderId: obj.id,
                    orderCode: obj.code,
                  });
                } else if (type == "finish") {
                  await initSkuPlanTable(obj.details,obj);
                  form.val("addProductionPlanFormDiv", {
                    orderId: obj.id,
                    orderCode: obj.selCode,
                    // shipmentTime: obj.deliveryTime,
                  });
                }
              }
            },
          });
        }
      });
      async function initSkuPlanTable(list,obj) {
        let skuIdList = list.map((v) => v.productDetailId);
        const { data } = await admin.reqPro(
          "enterprise/product/admin/productDetailWMS/list",
          {
            inIds: skuIdList.join(","),
          }
        );
        console.log(123,list);
        
        var listData = data.map((v) => {
          v.customerSkuCode = v.skuCode;
          v.customerSkuName = v.skuName;
          v.customerSkuSpec = v.skuSpec;
          v.planNature = "entirety";
          v.outputTime = "";
          v.shipmentTime = "";
          v.bookId = "";
          v.bookCode = "";
          v.remark = "";
          v.productDetailId = v.id;
          if(obj){
            if($("#planSource").val() === "order"){
              v.shipmentTime = obj.deliveryTime;
            }else if($("#planSource").val() === "finish"){
                 v.shipmentTime = obj.planOnTime;
            }
          }
          if($("#planSource").val() === "order"){
            console.log(22222222);
            
            if(list.find((v1)=>v1.productDetailId === v.id)){
              
              v.productionQuantity = list.find((v1)=>v1.productDetailId === v.id).quantity;
            }
          }else if($("#planSource").val() === "finish"){
            if(list.find((v1)=>v1.productDetailId === v.id)){
              v.productionQuantity = list.find((v1)=>v1.productDetailId === v.id).selQuality;
            }
          }
          return v;
        });
        console.log(12,listData);
        console.log(12,data);
        window.setTimeout(()=>{
          table.reload("skuPlanTable", { data: listData });
        },100)
      }
      form.on("submit(addProductionPlanExamine)", function (d) {
        let status = $(d.elem).data("type");
        submitFun(d, status);
        return false;
      });
      form.on("submit(addProductionPlanFormSubmit)", function (d) {
        let status = $(d.elem).data("type");
        submitFun(d, status);
        return false;
      });
      $("#openImgTable").click(async function () {
        if (!$("#bookId").val()) {
          layer.msg("请先选择基准书", { icon: 2 });
          return false;
        }
        const res = await admin.reqPro(
          "enterprise/benchmarkBook/admin/benchmarkBook/detail/" +
          $("#bookId").val()
        );
        console.log(123, res.data.drawInfos);
  
        admin.formOpen({
          area: ["55%", "45%"],
          title: "附件列表",
          content: `<div id="imgTable" style='height:100%;overflow: auto;'>
              <table id="imgTableList" lay-filter="imgTableList">
              </table>
              </div>`,
          success: function () {
            table.render({
              elem: "#imgTableList",
              data: res.data.drawInfos,
              page: false,
              limit: 99999,
              cols: [
                [
                  { type: "numbers", title: "序号" },
                  { field: "drawName", title: "图片名称" },
                  { field: "drawUrl", title: "图片地址" },
                  {
                    title: "操作",
                    align: "center",
                    width: 160,
                    templet: function (d) {
                      return `<a class="layui-btn layui-btn-xs" type="button" lay-event="preview">预览</a>`;
                    },
                  },
                ],
              ],
            });
            table.on("tool(imgTableList)", function (obj) {
              if (obj.event === "preview") {
                admin.formOpen({
                  title: "图片预览",
                  area: ["80%", "80%"],
                  content: `<div style='overflow: hidden;height:100%;display:flex;justify-content: center;
    '><img style="height:100%" src="${obj.data.drawUrl}"/></div>`,
                });
              }
            });
          },
        });
      });
      $("#bookIdBox").click(function () {
        let customerSkuCode = $("#customerSkuCode").val();
        if (!customerSkuCode) {
          layer.msg("请先选择物料", { icon: 2 });
          return false;
        }
        // data.productDetailId = data.id;
        // admin.putTempData("benData", data ? data : null);
        // 展示ben的页面 显示物料类型
        let obj = form.val("addProductionPlanFormDiv");
        // data.productDetailId = data.id;
        admin.putTempData("benData", obj ? obj : null);
        admin.formOpen({
          area: "1400px",
          offset: "35px",
          title: "基准书管理",
          path: "components/product/benManager.html",
          success: function () {
            parentData.typeName = "redio";
          },
          end: async function () {
            console.log(childData.obj);
            let obj = childData.obj ? childData.obj : {};
            if (obj.statusName == "待初审") {
              layer.msg("基准书状态为待初审，无法生成生产计划！", { icon: 2 });
              return false;
            }
            form.val("addProductionPlanFormDiv", {
              bookId: obj.id,
            });
            if (obj.id) {
              if (obj.drawUrl) {
                form.val("addProductionPlanFormDiv", {
                  accessoryFileId: obj.drawUrl,
                });
                $("#accessoryPath").html(
                  "<a href='" +
                  obj.drawUrl +
                  "' target='_blank'>" +
                  obj.drawUrl +
                  "</a>"
                );
                // $("#accessoryBtn").hide();
                $("#accessoryFileId").val(obj.drawUrl);
              }
            }
          },
        });
      });
      $("#addBookFun").click(function () {
        let productDetailId = $("#productDetailId").val();
        if (!productDetailId) {
          layer.msg("请先选择物料", { icon: 2 });
          return false;
        }
        admin.req(
          "enterprise/product/admin/productDetailWMS/get",
          { productDetailId },
          (res) => {
            if (res.code == 200) {
              admin.formOpen({
                area: ["80%", "85%"],
                title: "添加基准书",
                path: "components/res/benchmarkBook/skuPlanTable.html",
                success: function () {
                  parentData.eventName = "add";
                  let obj = { ...res.data, productDetailId };
                  delete obj.id;
                  // obj.productType = obj.productTypeId;
                  parentData.data = obj;
                  parentData.type = "生产计划列表";
                },
                end: function () {
                  initBenchmarkBookData(productDetailId);
                },
              });
            }
          }
        );
  
        return false;
      });
      function submitFun(d, status) {
        const formData = { ...d.field, status };
        formData.orderType = formData.planSource;
        formData.batchProductionPlansList = table.cache["skuPlanTable"];
        // if (formData.planNature == "process") {
        //   if (!formData.processId) {
        //     layer.msg("请选择工序", { icon: 2 });
        //     return false;
        //   }
        // }
  
        let isBookObj = formData.batchProductionPlansList.find((v) => {
          return !v.bookId;
        });
        if (isBookObj) {
          layer.msg("请选择料号名称为" + isBookObj.customerSkuCode + "的基准书", {
            icon: 2,
          });
          return false;
        }
        let isShipmentTimeObj = formData.batchProductionPlansList.find((v) => {
          return !v.shipmentTime;
        });
        if (isShipmentTimeObj) {
          layer.msg(
            "请输入料号名称为" +
            isShipmentTimeObj.customerSkuCode +
            "的生产截至时间",
            {
              icon: 2,
            }
          );
        }
        let isOutputTimeObj = formData.batchProductionPlansList.some((v) => {
          return !v.OutputTime;
        });
        if (isOutputTimeObj) {
          layer.msg(
            "请输入料号名称为" + isOutputTimeObj.customerSkuCode + "的交货时间",
            {
              icon: 2,
            }
          );
        }
        layer.load(2);
        console.log(123, formData);
  
        // return false;
        // if (nowData.eventName === "add") {
        admin.req(
          nowData.eventName === "add"
            ? "production/productionPlan/admin/productionPlan/addBatchPlan"
            : // ? "production/productionPlan/admin/productionPlan/add"
            "production/productionPlan/admin/productionPlan/update",
          JSON.stringify(formData),
          function (res) {
            layer.closeAll("loading");
            if (res.code == 200) {
              layer.msg(res.msg, { icon: 1 });
              table.reload("productionPlanTable");
              layer.closeAll("page");
              if (
                nowData.planSourceType == "order" ||
                nowData.planSourceType == "finish"
              ) {
                // 弹窗 是否跳转生产计划页面
                let layInex = layer.confirm(
                  "添加成功，是否跳转生产计划页面？",
                  { icon: 3, title: "提示" },
                  function (index) {
                    location.href = "index.html#/productionPlan/productionPlan";
                    layer.close(layInex);
                  }
                );
              }
            } else {
              layer.msg(res.msg, { icon: 2 });
            }
          },
          nowData.eventName === "add" ? "POST" : "PUT",
          false,
          "application/json"
        );
        // }
        return false;
      }
    });
  </script>
  <style>
    #skuPlanTable .layui-input-block {
      margin-left: 130px;
    }
  
    #skuPlanTable .layui-form-label {
      width: 100px;
    }
  
    #skuPlanTableModel .layui-table-cell {
      overflow: visible !important;
    }
  </style>